package com.it.security.controller;

import com.it.security.pojo.CommonResult;
import com.it.security.pojo.Permission;
import com.it.security.pojo.Role;
import com.it.security.pojo.User;
import com.it.security.service.*;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.pl.REGON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    RoleService roleService;
    @Autowired
    PermissionService permissionService;

    @Autowired
    RolerPermissionService rolerPermissionService;

    @Autowired
    UserRoleService userRoleService;

    @Autowired
    MyUserDetailsService myUserDetailsService;


    @RequestMapping("/user")
    public User getUserById(){

        log.info("请求user");
        User user = userService.getUserById((long) 1);
        log.info(user.toString());
        return user;

    }

    @RequestMapping("/role")
    public Role getRoleById(){

        log.info("请求role");
        Role role = roleService.getRoleById(1);
        return role;
    }

    @RequestMapping("/permission")
    public Permission getPermission(){
        log.info("请求permisson");
        Permission permission = permissionService.getPermissionById(1);
        return permission;
    }

    @RequestMapping("/rolerPermission")
    public List<Integer> getPermissionByRolerId(){
        List<Integer> list = rolerPermissionService.getPermissionByRolerId(1);
        return list;

    }

    @RequestMapping("roleid")
    public CommonResult<List<Integer>> getRolerId(){
        log.info("根据用户查询角色");
        List<Integer> list = userRoleService.getRoleByUserId(1);
        return new CommonResult(200,"请求成功",list);
    }

    @RequestMapping("/r")
    public CommonResult<List<Role>> test(){
        log.info("根据用户id查询角色");
        List<Role> list = roleService.getRoleByUserId(1);
        log.info(list.toString());
        return new CommonResult<>(200,"查询成功",list);
    }
    /**
     * 根据用户名查询权限列表
     */
    @RequestMapping("ah")
    public CommonResult test2(){
        log.info("根据用户名查询权限列表");
        List<GrantedAuthority> authoritys = myUserDetailsService.getAuthorityByUser("admin");
        log.info(authoritys.toString());
        return new CommonResult(200,"查询成功",authoritys);

    }

    @RequestMapping("/t")
    @PreAuthorize("hasAuthority('TEST_UTILS')")
    public String test1(){
        return "该请求需要 ROLE_TEST角色 或者 TEST_UTILS权限才能访问 其它均不行";
    }
}

